// pages/index_detail/index_detail.js
var app = getApp();//引用app.js
var commonURL = app.data.baseURL;
var commonURLWW = app.data.testURL;
var commonURLYY = app.data.newURL;
var appid = app.data.appid;
var animation = wx.createAnimation({
    duration: 600,  //动画持续时间，单位ms，默认值 400
    timingFunction: 'linear'//linear  动画一直较为均匀
});
Page({
    data: {
        "price": {
            "dandu": "",
            "tuangou": "",
            "num": "",
            "cart_num": '1'
        },
        "guige": {
            img: "",
            price: "0.00",
            list: [
                {
                    id: "",
                    name: ""
                }
            ]
        },
        "guigeOptions": [
            // {
            //   costprice:"0.03",
            //   id:"8697",
            //   marketprice:"0.01",
            //   productprice:"0.02",
            //   specs:"4110",
            //   stock:"11105",
            //   thumb:"",
            //   title:"黄"
            // }
        ],
        "currentItem": [
            // {
            //   title:"",
            //   item:"",
            // }
        ],
        "disabledGuige": "none",
        "animation": "",//规格弹窗
        "imgUrls": [],
        "detail": {
            id: "",
            title: "",
            shichangprice: "",
            salenum: "",
            unit: "",
            img: "",
            kucun: "",
            selltype: "",
            deliverytype: ""
        },
        "navTab": ["图文详情", "商品属性"],
        "currentNavtab": "0",
        "likes": [
            // {
            //   img:"../../images/index/detail1.jpg",
            //   title:"苹果1苹果苹果苹果苹果苹果",
            //   price:"28.00"
            // }
        ],
        "close": "none",//关闭图标属性
        "xiangqing": {},
        "shuxing": [
            // {
            //   text1:"11111",
            //   text2:"22222"
            // }
        ],
        "show_canvas": 'none',
        "tuan_id": ''
    },
    onLoad: function (options) {
        // 页面初始化 options为页面跳转所带来的参数
        var indexid = options.id;
        console.log(indexid);
        var that = this;
        var likes = [];
        var imgUrls = [];
        var shuxing = [];
        var xiangqing = "";
        wx.request({//ajax加载商品详情
            url: commonURL + 'op=goods_detail',
            data: {
                id: indexid
            },
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                console.log(res.data);
                var data = res.data;
                if (data.advs.length == 0) {//获取轮播图片
                    imgUrls.push(data.gimg);
                } else {
                    for (var j = 0; j < data.advs.length; j++) {
                        imgUrls.push(data.advs[j].thumb);
                    }
                }
                if (data.params.length == 0) {
                    shuxing = [{text1: "暂无属性信息"}];
                } else {
                    for (var i = 0; i < data.params.length; i++) {//获取属性信息
                        var obj = {};
                        obj["text1"] = data.params[i].title;
                        obj["text2"] = data.params[i].value;
                        shuxing.push(obj);
                    }
                }
                if (data.gdesc == "") {
                    xiangqing = "暂无详情信息";
                } else {
                    xiangqing = data.gdesc;
                }
                that.setData({
                    xiangqing: that.escapeHtml(xiangqing).replace(/<img /g, '<img mode="widthFix" style="width:100%;" ')
                })
                that.saveStore(data.stores);
                that.setData({
                    "imgUrls": imgUrls,
                    "detail": {
                        id: data.id,
                        title: data.gname,
                        goodsdesc: that.escapeHtml(data.goodsdesc),
                        shichangprice: data.mprice,
                        salenum: data.salenum,
                        unit: data.unit,
                        img: data.gimg,
                        yunfei: "",
                        kuncun: data.gnum,
                        selltype: data.selltype,
                        deliverytype: data.deliverytype,
                        hasoption: data.hasoption,
                        weight: data.weight,
                        isshow: data.isshow,
                        gnum: data.gnum
                    },
                    "price": {
                        dandu: data.oprice,
                        tuangou: data.gprice,
                        num: data.groupnum,
                        "cart_num": '1'
                    },
                    //"xiangqing":xiangqing,
                    "shuxing": shuxing
                });
            }
        })
        // wx.request({//ajax加载猜你喜欢
        //   url: commonURL+'op=goods_rand',
        //   data: {},
        //   header: {
        //       'content-type': 'application/json'
        //   },
        //   success: function(res) {
        //     //console.log(res.data.list)
        //     if(res.data.list.length<1){return false}
        //     for(var i=0;i<res.data.list.length;i++){
        //       var obj={};
        //       obj["id"]=res.data.list[i].id;
        //       obj["gimg"]=res.data.list[i].gimg;
        //       obj["title"]=res.data.list[i].gname;
        //       obj["price"]=res.data.list[i].gprice;
        //       obj["selltype"]=res.data.list[i].selltype;
        //       likes.push(obj);
        //     }
        //     that.setData({
        //       "likes":likes
        //     })
        //   }
        // })
        this.get_code(options, this);     //获取小程序码
        this.get_detail_goods(indexid, this);//获取商品团信息
    },
    switchTab: function (e) {
        this.setData({
            currentNavtab: e.currentTarget.dataset.idx
        });
    },
    onReady: function () {
        // 页面渲染完成
    },
    onShow: function () {
        // 页面显示
        this.setData({
            disabledGuige: 'none'
        })
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
    },
    saveStore: function (data) {
        wx.setStorage({
            key: 'stores_tuan',
            data: data
        })
    },
    close: function (e) {
        this.setData({
            close: "none"
        })
    },
    open: function (e) {
        this.setData({
            close: "block"
        })
    },
    onPullDownRefresh: function () {
        var that = this;
        wx.startPullDownRefresh();
        that.get_detail_goods(that.data.detail.id, that);
    },
    chooseGG: function (e) {//选择规格
        var that = this;
        var title = e.currentTarget.dataset.title;
        var options = that.data.guigeOptions;
        var currentItem = that.data.currentItem;
        var key = e.currentTarget.dataset.key;
        var guige = that.data.guige;
        currentItem[key].title = title;
        currentItem[key].item = e.currentTarget.dataset.index;
        if (e.currentTarget.dataset.img) {
            guige.img = e.currentTarget.dataset.img
        }//如果规格图片存在，就替换图片
        for (var i = 0; i < options.length; i++) {
            for (var j = 0, ii = 0; j < currentItem.length; j++) {
                if (currentItem[j].title == "") {
                    that.setData({
                        "currentItem": currentItem,
                        "guige": guige
                    })
                    return false;
                }
                var patt1 = new RegExp(currentItem[j].title);
                var result = patt1.test(options[i].title);
                result && ii++;
            }
            if (currentItem.length == ii) {
                var price = "";
                that.data.istuan ? price = options[i].marketprice : price = options[i].productprice;
                guige.price = price;
            }
        }
        that.setData({
            "currentItem": currentItem,
            "guige": guige
        })
    },
    onShareAppMessage: function () {//分享页面
        return {
            title: this.data.detail.title,
            path: '/pages/detail_jielong/detail_jielong?id=' + this.data.detail.id
        }
    },
    gotoIndexDetail: function (e) {
        var _selltype = e.currentTarget.dataset.selltype;
        if (_selltype == '0') {
            wx.redirectTo({
                url: '../index_only_detail/index_only_detail?id=' + e.currentTarget.dataset.id,
            })
        } else {
            wx.redirectTo({
                url: '../index_detail/index_detail?id=' + e.currentTarget.dataset.id,
            })
        }
    },
    gotoBuyPage: function () {//规格弹窗，确定按钮
        var that = this;
        for (var i = 0; i < that.data.currentItem.length; i++) {
            if (that.data.currentItem[i].item == "-1") {//判断是否选中规格
                wx.showToast({
                    title: '请选择规格',
                    icon: 'loading',
                    duration: 1500
                })
                return false;
            }
        }
        wx.removeStorage({key: 'address'});
        for (var jj = 0, title = ""; jj < that.data.currentItem.length; jj++) {
            title += ("+" + that.data.currentItem[jj].title);
        }
        var dataDetail = {
            id: that.data.detail.id,
            title: that.data.detail.title,
            price: that.data.guige.price,
            img: that.data.detail.img,
            selltype: that.data.detail.selltype,
            deliverytype: that.data.detail.deliverytype,
            weight: that.data.detail.weight,
            optionname: title.slice(1),
            num: that.data.price.cart_num
        }
        wx.setStorage({
            key: "indexBuyDetail",
            data: dataDetail
        })
        wx.navigateTo({
            url: '../index_buy/index_buy?istuan=true&tuan_id=' + that.data.tuan_id,
        })
    },
    gotoBuy_tuan: function (e) {
        var that = this;
        var {isshow, gnum} = this.data.detail;
        if(isshow == '3' || gnum == '0') {
            wx.showToast({
                title: '售罄',
                icon: 'loading',
                duration: 2000
            })
            return false;
        }
        if (that.data.detail.hasoption == "1") {//有规格产品
            //弹出规格选择框
            that.ajaxGuige(that);//加载规格数据
            that.openGuige(that, true);
        } else {//无规格产品
            if (that.data.detail.kucun < 1) {
                wx.showToast({
                    title: '库存不足,无法购买',
                    icon: 'loading',
                    duration: 2000
                })
            } else {
                that.tiaozhuanTuan();//调用跳转函数
            }
        }
    },
    gotoBuy_dan: function (e) {
        var that = this;
        if (that.data.detail.hasoption == "1") {//有规格产品
            //弹出规格选择框
            that.ajaxGuige(that);
            that.openGuige(that, false);
        } else {//无规格产品
            if (this.data.detail.kucun < 1) {
                wx.showToast({
                    title: '库存不足,无法购买',
                    icon: 'loading',
                    duration: 2000
                })
            } else {
                that.tiaozhuanDan();//调用跳转函数
            }
        }
    },
    closeGuige: function () {
        var that = this;
        animation.height("0").step();
        that.setData({
            animation: animation.export() //关闭规格选择
        })
        setTimeout(function () {
            that.setData({disabledGuige: "none"});
        }, 600)
    },
    openGuige: function (that, istuan) {//选择规格动画
        that.setData({
            disabledGuige: "block"
        });
        animation.height("700rpx").step();
        that.setData({
            animation: animation.export(),//输出动画
            istuan: istuan
        })
    },
    tiaozhuanDan: function () {//单买跳转函数
        wx.removeStorage({key: 'address'});//清除缓存，修复地址不对应bug
        var dataDetail = {
            id: this.data.detail.id,
            title: this.data.detail.title,
            price: this.data.price.dandu,
            img: this.data.detail.img,
            selltype: this.data.detail.selltype,
            deliverytype: this.data.detail.deliverytype,
            weight: this.data.detail.weight
        }
        wx.setStorage({
            key: "indexBuyDetail",
            data: dataDetail
        })
        wx.navigateTo({
            url: '../index_buy/index_buy',
        })
    },
    tiaozhuanTuan: function () {//团购跳转函数
        wx.removeStorage({key: 'address'});
        var dataDetail = {
            id: this.data.detail.id,
            title: this.data.detail.title,
            price: this.data.price.tuangou,
            img: this.data.detail.img,
            selltype: this.data.detail.selltype,
            deliverytype: this.data.detail.deliverytype,
            weight: this.data.detail.weight,
        }
        wx.setStorage({
            key: "indexBuyDetail",
            data: dataDetail
        })
        wx.navigateTo({
            url: '../index_buy/index_buy?istuan=true&tuan_id=' + this.data.tuan_id,
        })
    },
    ajaxGuige: function (that) {
        var ajaxguige = wx.getStorageSync('guige');
        if (ajaxguige.id == that.data.detail.id) {//先判断该商品规格是否存在缓存中，否则ajax加载数据
            var data = ajaxguige.allspecs;
            var currentItem = [];
            for (var i = 0; i < data.length; i++) {
                currentItem.push({title: "", item: "-1"});
            }
            if (data.length < 1) {
                return false
            }
            that.setData({
                guige: {
                    img: that.data.detail.img,
                    price: "0.00",
                    list: data
                },
                guigeOptions: ajaxguige.options,
                currentItem: currentItem
            })
        } else {
            wx.request({
                url: commonURL + 'op=goods_guige',
                data: {
                    id: that.data.detail.id
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    console.log(res.data)
                    var data = res.data.allspecs;
                    var currentItem = [];
                    for (var i = 0; i < data.length; i++) {
                        currentItem.push({title: "", item: "-1"});
                    }
                    if (data.length < 1) {
                        return false
                    }
                    that.setData({
                        guige: {
                            img: that.data.detail.img,
                            price: "0.00",
                            list: data
                        },
                        guigeOptions: res.data.options,
                        currentItem: currentItem
                    })
                    var dataguige = res.data;
                    dataguige.id = that.data.detail.id;
                    wx.setStorage({//把规格存储在缓存中
                        key: 'guige',
                        data: dataguige,
                    })
                }
            })
        }
    },
    escapeHtml: function (text) {
        var a = text.replace(/(\&lt;)/g, "<");
        var b = a.replace(/(\&gt;)/g, ">");
        var c = b.replace(/(\&amp;)/g, "\&");
        var d = c.replace(/(\&quot;)/g, "\"");
        return d;
    },
    getimg: function () {
        var that = this;
        //生成图片
        wx.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: function (res) {
                console.log(res.tempFilePath);
                var imgsrc = res.tempFilePath;
                //存入相册
                that.setData({
                    imgg: imgsrc
                })
                wx.previewImage({
                    current: that.data.imgg, // 当前显示图片的http链接
                    urls: [that.data.imgg] // 需要预览的图片http链接列表
                })
            }
        })
    },
    get_code: function (options, that) {
        wx.request({                   //获取二维码
            url: commonURLWW + 'op=base64_decode',
            data: {
                openid: app.data.openid,
                orderno: undefined,
                appid: appid,
                secret: app.data.secret,
                path: "pages/detail_jielong/detail_jielong",
                scene: undefined
            },
            method: 'GET',
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                console.log(res);
                that.setData({
                    XCXimg: res.data
                })
                // wx.downloadFile({
                //   url: res.data,
                //   success: function (response) {
                //     console.log(response);
                //     wx.playVoice({
                //       filePath: response.tempFilePath
                //     })
                //     that.setData({
                //       code_img: response.tempFilePath
                //     })
                //   }
                // })
            }
        })
    },
    onshow_canvas: function () {
        // const ctx = wx.createCanvasContext('myCanvas')

        // // ctx.draw();
        // ctx.drawImage(this.data.gimg, 0, 0, 300, 150);
        // ctx.drawImage(this.data.code_img, 0, 0, 150, 150);
        // ctx.draw();
        this.setData({
            show_canvas: 'block'
        })
    },
    close_canvas: function () {
        this.setData({
            show_canvas: 'none'
        })
    },
    //无规格时，加按钮
    add_cart: function () {
        var that = this;
        var kucun = this.data.detail.kucun;
        var nowNum = this.data.price.cart_num;
        if (Number(nowNum) > Number(kucun)) {
            wx.showToast({
                title: '库存不足',
                icon: 'loading',
                duration: 2000
            })
            return;
        } else {
            var price = that.data.price;
            price['cart_num'] = nowNum - 0 + 1;
            that.setData({
                "price": price
            })
        }
    },
    //减按钮
    minus: function () {
        var that = this;
        var nowNum = this.data.price.cart_num;
        if (Number(nowNum) == 1) {
            return;
        } else {
            var price = that.data.price;
            price['cart_num'] = nowNum - 1;
            that.setData({
                "price": price
            })
        }
    },
    get_detail_goods: function (gid, that) {
        wx.request({//ajax加载团详情
            url: commonURLYY + 'op=detail_goods',
            data: {
                gid: gid,
                openid: app.data.openid
            },
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                var isCanTuan = 0;
                var data = res.data;
                console.log(data);
                var detail_type = '0';
                if (data.status == '0') {
                    detail_type = '0';
                } else {
                    detail_type = '1';
                    var order = data.data.order;
                    var ordernew = [];
                    for (var i = order.length - 1; i >= 0; i--) {//团成员数据重构
                        order[i]['ptime'] = that.formatMsgTime(order[i]['ptime'] + '000');
                        order[i]['no'] = i + 1;
                        ordernew.push(order[i]);
                        // if (app.data.openid == order[i]['openid']){
                        //   isCanTuan+=1;
                        // }
                    }
                    if (data.data.group) {
                        isCanTuan = 0;
                    } else {
                        var group = data.data.group;
                        for (var i = group.length - 1; i >= 0; i--) {//团成员数据重构
                            if (app.data.openid == group[i]['openid']) {
                                isCanTuan += 1;
                            }
                        }
                    }
                    var len = ordernew.length - 1;
                    that.setData({
                        "order": ordernew,
                        "tuan_id": data.data.group.groupnumber,
                        "tuanzhang": ordernew[len]
                    })
                }
                wx.stopPullDownRefresh();
                that.setData({
                    "isCanTuan": isCanTuan,
                    "detail_tuan": res.data,
                    "detail_type": detail_type
                })

            }
        })
    },
    formatMsgTime: function (timespan) {

        var dateTime = new Date(Number(timespan));

        var year = dateTime.getFullYear();
        var month = dateTime.getMonth() + 1;
        var day = dateTime.getDate();
        var hour = dateTime.getHours();
        var minute = dateTime.getMinutes();
        var second = dateTime.getSeconds();
        var now = new Date();
        var now_new = Date.parse(now);  //typescript转换写法

        var milliseconds = 0;
        var timeSpanStr;

        milliseconds = now_new - timespan;

        if (milliseconds <= 1000 * 60 * 1) {
            timeSpanStr = '刚刚';
        }
        else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
            timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
        }
        else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
            timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
        }
        else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
            timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
        }
        else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) {
            timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute;
        } else {
            timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
            timeSpanStr = '刚刚';
        }
        return timeSpanStr;
    }
})